package com.subsequent.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.subsequent.pojo.Users;
import com.subsequent.service.UsersService;
import com.subsequent.mapper.UsersMapper;
import com.subsequent.utils.JwtService;
import com.subsequent.utils.Result;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
* @author 19329
* @description 针对表【users(系统用户表)】的数据库操作Service实现
* @createDate 2025-05-06 16:40:06
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{

    @Override
    public Result login(String username, String password) {
        if (Objects.equals(username, "") || Objects.equals(password, "")) {
            return Result.error(400, "账号或密码不能为空");
        }
        Users user = this.getOne(Wrappers.<Users>lambdaQuery().eq(Users::getUsername, username));
        if (user!=null ) {
            if (BCrypt.checkpw(password, user.getPassword())) {
                user.setPassword(null);

                Map<String, Object> claimMaps=new HashMap<>();
                claimMaps.put("id",user.getId());
                claimMaps.put("username",user.getUsername());
                String token = JwtService.createToken(claimMaps);
                return Result.success("登录成功",token);
            }else {
                return Result.error(401, "密码错误");
            }
        }else {
            return Result.error(401, "账号不存在");
        }
    }

    @Override
    public Result regist(Users user) {
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return Result.error(400, "用户名或密码不能为空");
        }

        Users tbUser = this.getOne(Wrappers.<Users>lambdaQuery().eq(Users::getUsername, user.getUsername()));
        if (tbUser != null) {
            return Result.error(402, "用户名已存在");
        }

        user.setPassword(BCrypt.hashpw(user.getPassword()));
        user.setCreatedAt(new Date());
        user.setPhone("12345678901"); // 一定要设置phone
        user.setUserType("1"); // 这里一定要赋值，1/2/3等，具体看你的业务

        boolean save = this.save(user);

        return save ? Result.success("注册成功", user) : Result.error(403, "注册失败");
    }
}